package com.shine.app.ui;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.shine.app.R;
import com.shine.app.bean.PlaceNearBean;
import com.shine.app.bean.SearchBean;
import com.shine.app.bean.UserBean;
import com.shine.app.bean.UserInfoBean;
import com.shine.app.bean.request.CredentialBean;
import com.shine.app.bean.responses.AuthenticateUserResponse;
import com.shine.app.bean.responses.ValidateResponse;
import com.shine.app.commons.Commons;
import com.shine.app.commons.UIHelper;
import com.shine.app.inject.InjectView;
import com.shine.app.inject.Injector;

public class SearchTeeTimeActivity extends SearchTeeTimeSlideviewActivity
		implements OnClickListener {

	@InjectView(R.id.search_location)
	private LinearLayout search_location_layout;
	@InjectView(R.id.search_near)
	private LinearLayout search_near_layout;
	@InjectView(R.id.search_location_double)
	private LinearLayout search_location_double_layout;
	@InjectView(R.id.search_location_name)
	private LinearLayout search_location_name_layout;
	@InjectView(R.id.search_location_nearme)
	private LinearLayout search_location_nearme_layout;

	@InjectView(R.id.search_name)
	private TextView name_textView;
	@InjectView(R.id.search_name_double)
	private TextView search_name_textView;
	@InjectView(R.id.search_name_near)
	private TextView near_name_textView;

	@InjectView(R.id.search)
	private Button search_button;
	@InjectView(R.id.login)
	private Button login_button;
	@InjectView(R.id.head_back)
	private ImageView head_backImageView;
	@InjectView(R.id.scroll)
	private ScrollView scrollView;

	private SearchBean searchBean = null;
	private AuthenticateUserAsyncTask authenticateUserAsyncTask = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchteetime_slideview);
		Injector.get(this).inject();

		initCalendarView();
		initCalendarDate(null);
		initCalendarDateView();

		initPlayerView();
		initRangeView();
		initSlidMenu();
		clickListener();
		initLoginButton();
		openLocationDialog();
		initPageViewData();
		if (appContext.isLogin()) {
			authenticateUser(appContext.getLoginInfo());
		}
	}

	private void authenticateUser(UserInfoBean userInfoBean) {
		authenticateUserAsyncTask = new AuthenticateUserAsyncTask();
		authenticateUserAsyncTask.execute(userInfoBean);
	}

	private void openLocationDialog() {
		boolean tag = appContext.isReadDataCache(Commons.LOCATION_KEY);
		name_textView.setText(R.string.chooselocation);
		near_name_textView.setText(R.string.searchnearme);
		if (tag) {
			ValidateResponse response = (ValidateResponse) appContext
					.readObject(Commons.LOCATION_KEY);
			if (response.isData()) {
				search_location_layout.setVisibility(View.GONE);
				search_near_layout.setVisibility(View.VISIBLE);
				search_location_double_layout.setVisibility(View.GONE);
			} else {
				search_location_layout.setVisibility(View.VISIBLE);
				search_near_layout.setVisibility(View.GONE);
				search_location_double_layout.setVisibility(View.GONE);
			}

		} else {
			Intent intent = new Intent(this, LocationDialogActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			this.startActivityForResult(intent, Commons.LISTVIEW_TAB_ONE);
		}
		if (!appContext.isReadDataCache(Commons.GPS_KEY)) {
			appContext.saveObject(new ValidateResponse(true), Commons.GPS_KEY);
			getMyLocation();
		}
	}

	private void clickListener() {
		search_near_layout.setOnClickListener(this);
		search_location_layout.setOnClickListener(this);
		search_location_name_layout.setOnClickListener(this);
		search_location_nearme_layout.setOnClickListener(this);
		search_player.setOnClickListener(this);
		search_date.setOnClickListener(this);
		search_time.setOnClickListener(this);
		search_button.setOnClickListener(this);
		login_button.setOnClickListener(this);
		head_backImageView.setOnClickListener(this);

		menu_bookingTableRow.setOnClickListener(this);
		menu_favoriteTableRow.setOnClickListener(this);
		menu_reviewTableRow.setOnClickListener(this);
		menu_editProfileTableRow.setOnClickListener(this);
		menu_socalTableRow.setOnClickListener(this);
		menu_passWordTableRow.setOnClickListener(this);
		menu_aboutTableRow.setOnClickListener(this);
		menu_contactTableRow.setOnClickListener(this);
		menu_privacyTableRow.setOnClickListener(this);
		menu_termTableRow.setOnClickListener(this);
		menu_cancelTeeTimeTableRow.setOnClickListener(this);
		logOutTextView.setOnClickListener(this);
		userLayout.setOnClickListener(this);
		slideview_button.setOnClickListener(this);
	}

	private void initPageViewData() {
		if (appContext.isReadDataCache(Commons.SEARCH_KEY)) {
			SearchBean searchBean = (SearchBean) appContext
					.readObject(Commons.SEARCH_KEY);
			int player = searchBean.getPlayer();
			int start = searchBean.getStartTime();
			int end = searchBean.getEndTime();
			initCalendarDate(searchBean.getDate());
			setCalendarDate();

			rangebar.setLeftIndex(start - 6);
			rangebar.setRightIndex(end - 6);
			starTextView.setText(instance.getRangebarTime(rangebar
					.getLeftIndex()));
			endTextView.setText(instance.getRangebarTime(rangebar
					.getRightIndex()));
			PlaceNearBean placeNearBean = searchBean.getPlaceNearBean();
			if (placeNearBean != null && placeNearBean.getLocation() != null) {
				search_name_textView.setText(placeNearBean.getLocation()
						.getFullName());
				search_location_layout.setVisibility(View.GONE);
				search_near_layout.setVisibility(View.GONE);
				search_location_double_layout.setVisibility(View.VISIBLE);
			} else {
				name_textView.setText(R.string.chooselocation);
				near_name_textView.setText(R.string.searchnearme);
				boolean tag = appContext.isReadDataCache(Commons.LOCATION_KEY);
				ValidateResponse response = (ValidateResponse) appContext
						.readObject(Commons.LOCATION_KEY);
				if (tag && response.isData()) {
					search_location_layout.setVisibility(View.GONE);
					search_near_layout.setVisibility(View.VISIBLE);
					search_location_double_layout.setVisibility(View.GONE);
				} else {
					search_location_layout.setVisibility(View.VISIBLE);
					search_near_layout.setVisibility(View.GONE);
					search_location_double_layout.setVisibility(View.GONE);
				}
			}
			setPlayer(player);
			dateTextView.setText(searchBean.getDate());
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		initLoginButton();
		initSlideviewData();
	}

	private void initLoginButton() {
		UserInfoBean user = appContext.getLoginInfo();
		if (user != null && user.getUser().isHasPassword()) {
			appContext.setLogin(true);
			login_button.setVisibility(View.GONE);
			privateLayout.setVisibility(View.GONE);
			menu_cancelTeeTimeLine.setVisibility(View.GONE);
			menu_cancelTeeTimeTableRow.setVisibility(View.GONE);
			userNameTextView.setText(user.getUser().getFirstName());
			logOutTextView.setText(R.string.menu_info_logout);
			menu_bookingTableRow.setClickable(true);
			menu_favoriteTableRow.setClickable(true);
			menu_reviewTableRow.setClickable(true);
			menu_editProfileTableRow.setClickable(true);
			menu_socalTableRow.setClickable(true);
			menu_passWordTableRow.setClickable(true);
		} else {
			login_button.setVisibility(View.VISIBLE);
			appContext.setLogin(false);
			privateLayout.setVisibility(View.VISIBLE);
			menu_cancelTeeTimeLine.setVisibility(View.VISIBLE);
			menu_cancelTeeTimeTableRow.setVisibility(View.VISIBLE);
			userNameTextView.setText(R.string.guest);
			logOutTextView.setText(R.string.menu_info_login);
			menu_bookingTableRow.setClickable(false);
			menu_favoriteTableRow.setClickable(false);
			menu_reviewTableRow.setClickable(false);
			menu_editProfileTableRow.setClickable(false);
			menu_socalTableRow.setClickable(false);
			menu_passWordTableRow.setClickable(false);
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		switch (v.getId()) {

		case R.id.search_location:
			packagedata();
			intent.setClass(this, LocationSearchActivity.class);
			intent.putExtra("searchBean", searchBean);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.search_near:
			packagedata();
			intent.setClass(this, LocationResultActivity.class);
			intent.putExtra("searchBean", searchBean);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.search_location_name:
			packagedata();
			intent.setClass(this, LocationSearchActivity.class);
			intent.putExtra("searchBean", searchBean);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.search_location_nearme:
			packagedata();
			intent.setClass(this, LocationResultActivity.class);
			intent.putExtra("searchBean", searchBean);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.search_player:
			if ((Boolean) search_player_imageView.getTag()) {
				closeLayout(layout_player, search_player_imageView);
			} else {
				closeTab();
				openLayout(layout_player, search_player_imageView);
			}
			break;

		case R.id.search_date:
			if ((Boolean) search_date_imageView.getTag()) {
				closeLayout(layout_date, search_date_imageView);
			} else {
				closeTab();
				openLayout(layout_date, search_date_imageView);
			}
			break;

		case R.id.search_time:
			if ((Boolean) search_time_imageView.getTag()) {
				closeLayout(layout_time, search_time_imageView);
			} else {
				closeTab();
				openLayout(layout_time, search_time_imageView);
			}
			break;

		case R.id.login:
			login_button.startAnimation(buttonAnimations);
			UIHelper.showLogin(this);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.search:
			search_button.startAnimation(buttonAnimations);
			break;

		case R.id.head_back:
			if (drawerLayout.isDrawerOpen(menu)) {
				drawerLayout.closeDrawer(menu);
			} else {
				drawerLayout.openDrawer(menu);
			}
			break;

		case R.id.menu_booking:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, ViewMyInfoTeeTimeActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_favorite:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, ViewMyInfoFavoriteActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_review:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, ViewMyInfoReviewActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_editprofile:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, ViewMyAccountProfileActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_social:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, ViewMyAccountSocialActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_password:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, ViewMyAccountPasswordActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_about:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, SlideAboutActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_contact:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, SlideContactActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_privacy:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, SlidePrivacypolicyActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_term:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, SlideTermsActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_cancel_teetime:
			drawerLayout.closeDrawer(menu);
			intent.setClass(this, SlideFindTeeTimeActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.menu_sign:
			drawerLayout.closeDrawer(menu);
			if (appContext.isLogin()) {
				appContext.Logout();
				initLoginButton();
			} else {
				UIHelper.showLogin(this);
				overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			}
			break;

		case R.id.slideview_button:
			drawerLayout.closeDrawer(menu);
			UIHelper.showLogin(this);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		default:
			break;
		}
	}

	protected void closeTab() {
		closeLayout(layout_player, search_player_imageView);
		closeLayout(layout_date, search_date_imageView);
		closeLayout(layout_time, search_time_imageView);
	}

	protected void openLayout(final LinearLayout layout, ImageView imageView) {
		imageView.setImageResource(R.drawable.searchlocation_top);
		imageView.setTag(true);
		layout.setVisibility(View.VISIBLE);
	}

	protected void closeLayout(final LinearLayout layout, ImageView imageView) {
		if ((Boolean) imageView.getTag()) {
			imageView.setImageResource(R.drawable.searchlocation_below);
			imageView.setTag(false);
			layout.setVisibility(View.GONE);
			if (layout_date == layout) {
				temporaryYear = selectYear;
				temporaryMonth = selectMonth;
				temporaryDay = selectDay;
				setCalendarDate();
			}
		}
	}

	private void packagedata() {
		searchBean = (SearchBean) appContext.readObject(Commons.SEARCH_KEY);
		if (searchBean == null) {
			searchBean = new SearchBean();
		}
		int numberOfPlayers = Integer
				.parseInt(getTextViewValues(playerTextView));
		int timeMin = rangebar.getLeftIndex() + 6;
		int timeMax = rangebar.getRightIndex() + 6;
		String day = getTextViewValues(dateTextView);
		searchBean.setDate(day);
		searchBean.setPlayer(numberOfPlayers);
		searchBean.setStartTime(timeMin);
		searchBean.setEndTime(timeMax);
		appContext.saveObject(searchBean, Commons.SEARCH_KEY);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == Commons.LISTVIEW_TAB_ONE && resultCode == RESULT_OK) {
			boolean tag = data.getBooleanExtra("result", false);
			appContext.saveObject(new ValidateResponse(tag),
					Commons.LOCATION_KEY);
			near_name_textView.setText(R.string.searchnearme);
			name_textView.setText(R.string.chooselocation);
			if (tag) {
				search_location_layout.setVisibility(View.GONE);
				search_near_layout.setVisibility(View.VISIBLE);
				search_location_double_layout.setVisibility(View.GONE);
			} else {
				search_location_layout.setVisibility(View.VISIBLE);
				search_near_layout.setVisibility(View.GONE);
				search_location_double_layout.setVisibility(View.GONE);
			}
		}
	}

	public class AuthenticateUserAsyncTask extends
			AsyncTask<Object, Integer, AuthenticateUserResponse> {
		private UserInfoBean userInfoBean = null;

		@Override
		protected AuthenticateUserResponse doInBackground(Object... params) {
			userInfoBean = (UserInfoBean) params[0];
			CredentialBean credentialBean = new CredentialBean(userInfoBean
					.getUser().getEmail(), userInfoBean.getPassword());
			AuthenticateUserResponse response = appContext
					.authenticateUser(credentialBean);
			return response;
		}

		@Override
		protected void onPostExecute(AuthenticateUserResponse response) {
			super.onPostExecute(response);
			if (response != null) {
				if (!response.isHasError()) {
					UserBean user = response.getData();
					UserInfoBean infoBean = new UserInfoBean();
					infoBean.setPassword(userInfoBean.getPassword());
					if (user != null) {
						user.setHasPassword(true);
						appContext.saveLoginInfo(userInfoBean);
					}
				} else {
					appContext.cleanLoginInfo();
				}
			}
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (drawerLayout.isDrawerOpen(menu)) {
				drawerLayout.closeDrawer(menu);
			} else {
				UIHelper.exitDialog(this);
			}
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		if (authenticateUserAsyncTask != null
				&& authenticateUserAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
			authenticateUserAsyncTask.cancel(true);
		}
		super.onDestroy();
	}
}
